<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item v-for="(item, index) in  inquiryZxj" :key="index" :label="item.label" :prop="item.prop">
        <el-input :placeholder="item.placeholder" v-model="queryParams[item.prop]" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['student:zxj:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['student:zxj:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['student:zxj:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['student:zxj:export']">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="zxjList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column v-for="(item, index) in  zxjItem" :key="index" :label="item.label" align="center"
        :prop="item.prop" />

      <el-table-column label="证件类型" align="center" prop="userIdcardtype">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.stu_user_cardtype" :value="scope.row.userIdcardtype" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['student:zxj:edit']">修改
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['student:zxj:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改助学金对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules">
        <!-- 姓名填写 -->
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入姓名" />
        </el-form-item>
        <!-- 证件类型选择 -->
        <el-form-item label="证件类型" prop="userIdcardtype">
          <el-select v-model="form.userIdcardtype" placeholder="请选择证件类型">
            <el-option v-for="dict in dict.type.stu_user_cardtype" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <!-- 证件号填写 -->
        <el-form-item label="证件号" prop="userIdno">
          <el-input v-model="form.userIdno" placeholder="请输入证件号" />
        </el-form-item>
        <!-- 证件号上传 -->
        <el-form-item label="上传文件" prop="uploadFile">
          <el-upload name="uploadFile" ref="upload" :data="form" :headers="headers" :auto-upload="false" :limit=limitNum
            accept=".png,.jpg" :on-exceed="exceedFile" :on-change="handleChange" :on-remove="handleRemove"
            :on-success="handleSuccess" :on-error="handleError" :http-request="httpRequest"
            :before-upload="beforeUploadFile" action="/dev-api/data/file/fileUpload" :file-list="fileList"
            :multiple="true" :show-file-list="true">
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <!-- 遍历助学金条件 -->
        <template v-for="item of zxjDialog">
          <el-form-item :label="item.label">
            <el-radio-group v-model="form[item.model]">
              <el-radio v-for="dict in dict.type.zxj_yes_no" :key="dict.value" :label="dict.value">{{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 遍历附件上传 -->
          <el-form-item label="上传文件" prop="uploadFile" v-if="form[item.model] != 0">
            <el-upload name="uploadFile" ref="upload" :data="form" :headers="headers" :auto-upload="false"
              :limit=limitNum accept=".png,.jpg" :on-exceed="exceedFile" :on-change="handleChange"
              :on-remove="handleRemove" :on-success="handleSuccess" :on-error="handleError" :http-request="httpRequest"
              :before-upload="beforeUploadFile" action="/dev-api/data/file/fileUpload" :file-list="fileList"
              :multiple="true" :show-file-list="true">
              <el-button size="small" type="primary">上传附件</el-button>
            </el-upload>
          </el-form-item>
        </template>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm1">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listZxj,
  getZxj,
  delZxj,
  addZxj,
  updateZxj,
  addFile,
} from "@/api/student/zxj";
import { getToken } from "@/utils/auth";
export default {
  name: "Zxj",
  dicts: ["zxj_yes_no", "stu_user_cardtype"],
  data() {
    return {
      //奖学金对话框
      zxjDialog: [
        {
          label: "脱贫家庭学生",
          model: "whetherfamilypoorstudents",
        },
        {
          label: "脱贫不稳定家庭学生",
          model: "whetherstudentsunstablefamilypoverty",
        },
        {
          label: "边缘易致贫家庭学生",
          model: "whetheredgeeasyfamilypovertystudents",
        },
        {
          label: "突发严重苦难户学生",
          model: "whethermassiveneedystudents",
        },
        {
          label: "原广东省户籍建档立卡家庭学生",
          model: "whetherguangddong",
        },
        {
          label: "特困供养人员",
          model: "whethermostneedysupportpersonnel",
        },
        {
          label: "孤儿",
          model: "whetherorphan",
        },
        {
          label: "特困职工儿女",
          model: "whetherverypoorworkerchildren",
        },
        {
          label: "城乡最低生活保障户",
          model: "urbanruralsecuritydoor",
        },
        {
          label: "城镇低收入困难家庭",
          model: "lowincomefamilies",
        },
        {
          label: "享受国家定期抚恤补助的优抚对象",
          model: "regularsubsidyobject",
        },
        {
          label: "学生本人残疾",
          model: "whetherdisability",
        },
        {
          label: "父亲为残疾人",
          model: "hisfatherfordisabl",
        },
        {
          label: "母亲为残疾人",
          model: "hismotherfordisabl",
        },
      ],
      // 查询奖学金表单
      inquiryZxj: [
        {
          label: "助学金序号",
          prop: "zxjId",
          placeholder: "请输入助学金序号",
        },
        {
          label: "用户序号",
          prop: "userId",
          placeholder: "请输入用户序号",
        },
        {
          label: "姓名",
          prop: "userName",
          placeholder: "请输入姓名",
        },
        {
          label: "证件号",
          prop: "userIdno",
          placeholder: "请输入证件号",
        },
      ],
      zxjItem: [
        {
          label: "助学金序号",
          prop: "zxjId",
        },
        {
          label: "用户序号",
          prop: "userId",
        },
        {
          label: "姓名",
          prop: "userName",
        },
        {
          label: "证件号",
          prop: "userIdno",
        },
        {
          label: "审核状态",
          prop: "status",
        },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 助学金表格数据
      zxjList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        zxjId: null,
        userId: null,
        userName: null,
        userIdno: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userName: [
          { required: true, message: "姓名不能为空", trigger: "blur" },
        ],
        userIdcardtype: [
          { required: true, message: "证件类型不能为空", trigger: "change" },
        ],
        userIdno: [
          { required: true, message: "证件号不能为空", trigger: "blur" },
        ],
      },
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      limitNum: 10,
      fileList: [],
      token: {
        accessToken: "",
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询助学金列表 */
    getList() {
      this.loading = true;
      listZxj(this.queryParams).then((response) => {
        this.zxjList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        zxjId: null,
        userId: null,
        userName: null,
        userIdcardtype: null,
        userIdno: null,
        whetherfamilypoorstudents: "0",
        whetherstudentsunstablefamilypoverty: "0",
        whetheredgeeasyfamilypovertystudents: "0",
        whethermassiveneedystudents: "0",
        whetherguangddong: "0",
        whethermostneedysupportpersonnel: "0",
        whetherorphan: "0",
        whetherverypoorworkerchildren: "0",
        urbanruralsecuritydoor: "0",
        lowincomefamilies: "0",
        regularsubsidyobject: "0",
        whetherdisability: "0",
        hisfatherfordisabl: "0",
        hismotherfordisabl: "0",
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        status: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.zxjId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加助学金";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const zxjId = row.zxjId || this.ids;
      getZxj(zxjId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改助学金";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.zxjId != null) {
            updateZxj(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addZxj(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const zxjIds = row.zxjId || this.ids;
      this.$modal
        .confirm('是否确认删除助学金编号为"' + zxjIds + '"的数据项？')
        .then(function () {
          return delZxj(zxjIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "student/zxj/export",
        {
          ...this.queryParams,
        },
        `zxj_${new Date().getTime()}.xlsx`
      );
    },

    exceedFile(files, fileList) {
      this.$message({
        message:
          "只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个",
        type: "danger",
      });
    },

    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      this.filelist = fileList;
    },
    // 文件移除时的钩子
    handleRemove(file, fileList) {
      this.filelist = fileList;
    },

    // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
    beforeUploadFile(file) {
      let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "png";
      const extension2 = testmsg === "jpg";
      let size = file.size / 1024 / 1024;
      if (!extension && !extension2) {
        this.$message({
          message: "上传文件只能是png、jpg!",
          type: "danger",
        });
      }
      if (size > 20) {
        this.$message({
          type: "danger",
          message: `文件大小不得超过20M!`,
        });
      }
      return extension || extension2;
    },

    // 文件上传成功时的钩子
    handleSuccess(res, file, fileList) {
      this.open = false;
      this.getList();
      this.$message({
        type: "danger",
        message: `文件上传成功!`,
      });
    },

    // 文件上传失败时的钩子
    handleError(err, file, fileList) {
      this.$message({
        type: "danger",
        message: `文件上传失败!`,
      });
    },
    submitForm1(form) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var upData = new FormData(); // 首先创建FormData对象
          this.$refs.upload.submit(); // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
          this.fileList.forEach(function (file) {
            upData.append("uploadFile", file, file.name); // 因为要上传多个文件，所以需要遍历一下才行
            // upData.append('file', this.file); 不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
          });
          //遍历表单中的其他参数
          for (let key in this.form) {
            //非空判断
            if (
              this.form[key] != null &&
              this.form[key] != "" &&
              this.form[key] != " "
            ) {
              upData.append(key, this.form[key]);
            }
          }
          //同理: 将每个参数都进行一次此操作 upData.appen(表单参数,form.表单参数)

          //接口调用
          addFile(upData).then((response) => {
            if (response.code === 200) {
              this.$modal.msgSuccess("上传成功！");
              this.$refs.upload.clearFiles(); //清空，同this.fileList=[]
              this.open = false;
              this.getList();
            } else {
              this.$modal.msgError("上传失败！");
              this.open = false;
              this.fileList = []; // 阻止上传的文件被重复添加，所以清空掉
            }
          });
        }
      });
    },

    // 自定义的上传函数
    httpRequest(param) {
      // 一般情况下是在这里创建FormData对象，但我们需要上传多个文件，为避免发送多次请求，因此在这里只进行文件的获取，param可以拿到文件上传的所有信息
      this.fileList.push(param.file);
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
